package com.lsk.admin.shop;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.jfinal.weixin.sdk.api.RedPackApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.lsk.applet.AppletService;
import com.lsk.qiniu.QiniuController;
import com.lsk.util.*;

import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.jfinal.plugin.activerecord.Db.save;

/**
 * Created by Administrator on 2018/7/16 0016.
 */
public class ShopServices {

    /**
     * 获取机构下的所有商品
     *
     * @return
     */
    public PageUtil commodityListService(int page, int limit, String key) {
        String sql = "SELECT *from shop_commodity where state!=3  ";
        if ("".equals(key) == false && "null".equals(key) == false && key != null) {
            sql += " and state=" + key;
        }
        sql += " order by createTime desc";
        PageUtil pageUtil = new PageUtil(page, limit, sql);
        return pageUtil;
    }

    public Record editCommodityService(String id) {
        String sql = "SELECT *from shop_commodity where id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 通过状态查询商品列表
     */
    public Map shopListByState(int page, int limit, String state) {

        String sql = "SELECT *from shop_commodity ";
        if (state.equals("") == false) {
            sql += " where state='" + state + "' ";
        }
        //  sql+=" ORDER BY createTime desc  ";

        PageUtil pageUtil = new PageUtil(page, limit, sql);
        List<Record> list = pageUtil.getList();
        int count = pageUtil.getTotalRows();
        for (int i = 0; i < list.size(); i++) {
            Record record = list.get(i);
            state = record.getStr("state");
            if ("0".equals(state)) {
                record.set("state", "未上架");
            } else if ("1".equals(state)) {
                record.set("state", "上架中");
            } else if ("2".equals(state)) {
                record.set("state", "已下架");
            }
            list.set(i, record);
        }
        Map map = new HashMap();
        map.put("code", 0);
        if (count > 0) {
            map.put("count", count);
            map.put("data", list);
        } else {
            map.put("count", 0);
            map.put("msg", "暂无数据");
        }
        return map;
    }

    /**
     * 删除商品
     */
    public ReturnData delCommodityService(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String sql = "update  shop_commodity set state=3 where id='" + id + "'";
        int del = Db.update(sql);
        if (del == 1) {
            returnData.setResult(true);
        } else {
            returnData.setResult(false);
        }
        return returnData;
    }

    /**
     * 注册商户
     */
    public ReturnData registerMerchantService(Map<String, String[]> map) throws Exception {
        ReturnData returnData = new ReturnData();
        String name = map.get("name")[0];//姓名
        String tel = map.get("tel")[0];//电话
        String address = map.get("address")[0];//地址
        String grade = map.get("grade")[0];//产品等级

        String userId = UtilUUID.getUUID();
        String salt = UtilUUID.getOrderIdByUUId();
        String password = AES.AESEncode(StringUtil.getPinYinHeadChar(name) + tel.substring(tel.length() - 4));
        Date date = new Date();
        String userCode = StringUtil.getPinYinHeadChar(name) + tel;
        String sql = "SELECT *from sys_user where userCode='" + userCode + "'";
        Record oldUser = Db.findFirst(sql);
        if (oldUser != null) {//账户已经存在
            returnData.setCode("111111");
            returnData.setMsg("账户已经存在");
        } else {
            Record user = new Record().set("id", userId).set("userCode", userCode).set("salt", salt)
                    .set("locked", "0").set("type", "1").set("phone", tel).set("adminUserId", "1")
                    .set("password", password).set("userName", name);
            boolean userBoolean = save("sys_user", "id", user);//保存用户
            Record org = new Record().set("name", name + "的店铺").set("tel", tel).set("person", name)
                    .set("address", address).set("createTime", date).set("startTime", date)
                    .set("endTime", DateUtil.getAfterDayDate("365")).set("adminUserId", userId)
                    .set("grade", grade);
            boolean orgBoolean = save("yx_org", "id", org);//保存用户
            if (userBoolean && orgBoolean) {//同时保存成功
                Map result = new HashMap();
                result.put("user", tel);
                result.put("password", AES.AESDncode(password));
                returnData.setData(result);
                returnData.setCode("000000");
                returnData.setMsg("保存成功");
            } else {//抛出异常，事务回滚
                throw new Exception();
            }
        }
        return returnData;
    }

    /**
     * 查询店铺-商品信息
     */
    public Map shopProductListData(String id, int page, int limit) {
        String sql = "SELECT\n" +
                "\tp.id as prouctId , p.productName,\n" +
                "\tp.productUnit,\n" +
                "\tIFNULL(shp.price,0) as price,\n" +
                "  shp.id\n" +
                "FROM\n" +
                "\tproduct p\n" +
                "LEFT JOIN shop_product shp ON p.id = shp.productId and shp.shopId='" + id + "' order by shp.id, shp.price desc  ";
        Map map = new HashMap();
        PageUtil pageUtil = new PageUtil(page, limit, sql);
        List<Record> list = pageUtil.getList();
        int count = pageUtil.getTotalRows();
        for (int i = 0; i < list.size(); i++) {
            Record record = list.get(i);
            String shpId = record.getStr("id");
            if (shpId == null || shpId == "") {
                record.set("state", "未配置信息");
            } else {
                record.set("state", "已配置");
            }
        }

        map.put("code", 0);
        if (count > 0) {
            map.put("count", count);
            map.put("data", list);
        } else {
            map.put("count", 0);
            map.put("msg", "暂无数据");
        }
        return map;
    }


    /**
     * 设定店家--商品信息
     *
     * @param id
     * @param money
     * @param state
     * @return
     */
    public ReturnData saveShopProductSettingService(String id, String money,
                                                    String state, String prouctId, String shopId) {
        ReturnData returnData = new ReturnData();
        boolean sa = false;
        Record shopProduct = new Record().set("shopId", shopId).set("productId", prouctId).set("price", money);
        /*判断操作*/
        if ("0".equals(state)) {//取消配置
            if (id == null || "null".equals(id) || "".equals(id)) {//本来就没有
                sa = true;
            } else {
                shopProduct.set("id", id);
                sa = Db.delete("shop_product", "id", shopProduct);
            }

        } else {//添加配置
            if (id == null || "null".equals(id) || "".equals(id)) {//该店家未设置该商品信息
                sa = save("shop_product", "id", shopProduct);
            } else {
                shopProduct.set("id", id);
                sa = Db.update("shop_product", "id", shopProduct);
            }
        }
        returnData.setResult(sa);
        return returnData;
    }


    /**
     * 保存店家信息
     *
     * @param map
     * @return
     */
    public ReturnData saveShopInfoServie(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        boolean result = false;
        String id = map.get("id")[0].trim();
        String name = map.get("name")[0].trim();
        String address = map.get("address")[0].trim();
        String principal = map.get("principal")[0].trim();
        String principalTel = map.get("principalTel")[0].trim();
        Record record = new Record().set("name", name).set("address", address)
                .set("principal", principal).set("principalTel", principalTel);
        if ("".equals(id) || id == null || "null".equals(id)) {//id为空
            record.set("id", UtilUUID.getUUID());
            result = save("shop", "id", record);
        } else {
            record.set("id", id);
            result = Db.update("shop", "id", record);
        }
        returnData.setResult(result);
        return returnData;
    }


    /**
     * 店铺详情
     *
     * @param id 店铺id
     * @return
     */
    public Record getShopInfoService(String id) {
        String sql = "SELECT *from shop where id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }


    /**
     * 商户列表数据
     */
    public Map shopListDataService(int page, int limit) {
        Map map = new HashMap();
        String sql = "SELECT *from shop";
        PageUtil pageUtil = new PageUtil(page, limit, sql);
        List<Record> list = pageUtil.getList();
        int count = pageUtil.getTotalRows();
        map.put("code", 0);
        if (count > 0) {
            map.put("count", count);
            map.put("data", list);
        } else {
            map.put("count", 0);
            map.put("msg", "暂无数据");
        }
        return map;
    }

    /**
     * 商品一级类别
     */
    public PageUtil shopClassOneService(int page, int limit, String grade, String id,String shopId) {
        String sql = "SELECT *from navigation where shopId='"+shopId+"' and grade=" + grade;
        String countSql = "SELECT count(id) FROM navigation WHERE shopId='"+shopId+"' and grade=" + grade;
        if (id != null) {
            sql += " and parentId = '" + id + "'";        //二级商品分类
        }
        sql += " ORDER BY number ";
        PageUtil pageUtil = new PageUtil(page, limit, sql, countSql);

        return pageUtil;
    }

    /**
     * 修改或新增商品类型
     */
    public Record editClassType(String id) {
        Record editClassType = null;
        if (id != null && id != "") {
            editClassType = Db.findFirst("select * from navigation where id=?", id);
        } else {
            editClassType = new Record();
        }
        List<Record> parentList = Db.find("select * from navigation where grade=0");       //查询所有父级
        editClassType.set("parentList", parentList);
        return editClassType;
    }


    /**
     * 保存商品分类
     */
    public ReturnData saveClassService(Map<String, String[]> map,String shopId) {
        ReturnData returnData = new ReturnData();
        try {

            String id = map.get("id")[0];
            String parentId = map.get("parentId")[0];
            String name = map.get("name")[0].trim();
            String number = map.get("number")[0].trim();
            String logo = map.get("logo")[0].trim();
            int grade = getClassGrade(parentId);
            Record cla = new Record();
            cla.set("name", name).set("number", number).set("parentId", parentId).set("grade", grade).set("logo", logo).set("shopId",shopId);
            boolean sa = false;
            if ("".equals(id)) {//无id值为新增
                cla.set("id", UuidUtil.get32UUID());
                sa = save("navigation", "id", cla);
            } else {
                cla.set("id", id);
                sa = Db.update("navigation", "id", cla);
            }
            if (sa) {
                returnData.setMsg("保存成功");
                returnData.setCode("000000");
            } else {
                returnData.setMsg("保存是吧");
                returnData.setCode("111111");
            }
        } catch (NullPointerException e) {
            returnData.setResult(false);
            returnData.setMsg("缺少必填项");
            returnData.setCode("000000");
        }
        return returnData;
    }

    /**
     * 删除商品分类
     */
    public ReturnData delClassService(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String delSql = "DELETE from navigation where id=?";
        int de = Db.delete(delSql, id);
        if (de > 0) {//删除成功
            delSql = "DELETE from commodity_class where parentId=?";
            Db.delete(delSql, id);
            returnData.setCode("000000");
            returnData.setMsg("删除成功");

        } else {
            returnData.setCode("111111");
            returnData.setMsg("删除失败");
        }
        return returnData;
    }

    /**
     * 根据分类ID 查询出对应的分类信息
     */
    public Record getClassById(String id) {
        String sql = "SELECT *from navigation WHERE id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 根据父级ID  查询出对应的权限级别
     */
    public int getClassGrade(String parentId) {
        int result = 0;
        Record parent = getClassById(parentId);
        if (parent != null) {
            result = parent.getInt("grade") + 1;
        } else {
            result = 0;
        }
        return result;
    }

    /**
     * 组装商品类型数据（select标签）
     */
    public List<Record> assembleSelectData() {
        String sqlOneClaess = "SELECT *from shop_class where parentId=0";
        List<Record> list = Db.find(sqlOneClaess);
        /*遍历查询出二级类别*/
        for (int i = 0; i < list.size(); i++) {
            Record temp = list.get(i);
            String id = temp.getStr("id");
            String sql = "SELECT *from shop_class where parentId='" + id + "'";
            List<Record> twoList = Db.find(sql);
            temp.set("twoList", twoList);
            list.set(i, temp);
        }
        return list;
    }

    /**
     * 商品轮播图文件上传service
     */
    public int slideshowUploadService(List<UploadFile> uploadFiles, String commodityId, String id) {
        String projectPath = new GlobalParameter().projectPath;
        int code = 0;
        List<Record> list = new ArrayList<>();
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {
                Record imgPathRecord = new Record();
                UploadFile temp = uploadFiles.get(i);
                String fileName = temp.getFileName();
                /*copy图片到指定目录*/
                String uuid = UtilUUID.getUUID();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String slideshow = projectPath + "/uploadImg/commodity-slideshow" + "/" + commodityId + "/" + uuid + "/";
                String newImgPath = slideshow + uuid + "." + suffix;
                FileTailor.copyFile(temp.getUploadPath() + "/" + fileName, slideshow, newImgPath);
                /*压缩图片*/
                FileTailor fileTailor = new FileTailor();
                Syslog.info(newImgPath);
                String prevfix = "slideshow-";//缩略图前缀
                fileTailor.thumbnailImage(newImgPath, 480, 800, prevfix, false);
                String imgUrl = "uploadImg/commodity-slideshow" + "/" + commodityId + "/" + uuid + "/" + uuid + "." + suffix;
                Syslog.info("图片路径为：" + imgUrl);
                imgPathRecord.set("id", uuid).set("commodityId", commodityId).set("number", i)
                        .set("path", "/" + imgUrl).set("timestamp", System.currentTimeMillis());
                if ("".equals(id) || id == null) {//id为空

                } else {
                    imgPathRecord.set("id", id).remove("number").remove("commodityId");
                }
                list.add(imgPathRecord);
            }
            if ("".equals(id) || id == null) {//id为空
                Db.batchSave("shop_commodity_imgpath", list, list.size());
            } else {
                /*图片原路径*/
                Db.batchUpdate("shop_commodity_imgpath", list, list.size());
            }

        } catch (Exception e) {
            Syslog.error(e);
            code = 1;
        }
        return code;
    }

    /**
     * 商品信息富文本图片上传 Service
     */
    public Map commodityMessageImgUploadService(List<UploadFile> uploadFiles, String commodityId,String upToken) {
        Map map = new HashMap();
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {

                UploadFile temp = uploadFiles.get(i);

                QiniuController qiniuController=new QiniuController();

                String uploadPath=temp.getUploadPath()+temp.getFileName();

                String imgUrl=QiNiuConfig.Quickdomain+ qiniuController.UploadFileByFile(uploadPath, "ticketMessage/"

                        +UtilUUID.getUUID()+"."+temp.getContentType(), upToken);

                Syslog.info("图片路径为：" + imgUrl);
                map.put("code", "0");
                map.put("msg", "上传成功");
                Map data = new HashMap();
                data.put("src", imgUrl);
                data.put("title", "");
                map.put("data", data);

            }

        } catch (Exception e) {
            Syslog.error(e);
            map.put("code", "1");
            map.put("msg", e.toString());

        }
        return map;
    }

    /**
     * 商品详情富文本图片上传 Service
     */
    public Map commodityParticularsImgUpload(List<UploadFile> uploadFiles, String commodityId) {
        String projectPath = new GlobalParameter().projectPath;
        Map map = new HashMap();
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {
//                UploadFile temp = uploadFiles.get(i);
//                String fileName = temp.getFileName();
//                /*copy图片到指定目录*/
//                String uuid = UtilUUID.getUUID();
//                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//                String slideshow = projectPath + "/uploadImg/commodity-particulars" + "/" + commodityId + "/" + DateUtil.getDay() + "/";
//                String newImgPath = slideshow + uuid + "." + suffix;
//                FileTailor.copyFile(temp.getUploadPath() + "/" + fileName, slideshow, newImgPath);
//                /*压缩图片*/
//                FileTailor fileTailor = new FileTailor();
//                Syslog.info(newImgPath);
//                String prevfix = "commodityParticulars-";//缩略图前缀
//                Image img = ImageIO.read(temp.getFile());
//                int height = img.getHeight(null);//当前文件的高
//                fileTailor.thumbnailImage(newImgPath, 425, height, prevfix, true);
//                String imgUrl = "http://" + GlobalParameter.domain + "/uploadImg/commodity-particulars" + "/" + commodityId + "/" + DateUtil.getDay() + "/" + prevfix + uuid + "." + suffix;
//                Syslog.info("图片路径为：" + imgUrl);
//                map.put("code", "0");
//                map.put("msg", "上传成功");
//                Map data = new HashMap();
//                data.put("src", imgUrl);
//                data.put("title", "");
//                map.put("data", data);

            }

        } catch (Exception e) {
            Syslog.error(e);
            map.put("code", "1");
            map.put("msg", e.toString());

        }
        return map;
    }

    /**
     * 商品类别logo图片上传 Service
     */
    public Map classLogoImgUpload(List<UploadFile> uploadFiles, String commodityId) {
        String projectPath = new GlobalParameter().projectPath;
        Map map = new HashMap();
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {
                UploadFile temp = uploadFiles.get(i);
                String fileName = temp.getFileName();
                /*copy图片到指定目录*/
                String uuid = UtilUUID.getUUID();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String slideshow = projectPath + "/uploadImg/commodity/commodityClass/" + commodityId + "/logo" + "/" + DateUtil.getDay() + "/";
                String newImgPath = slideshow + uuid + "." + suffix;
                FileTailor.copyFile(temp.getUploadPath() + "/" + fileName, slideshow, newImgPath);
                /*压缩图片*/
                FileTailor fileTailor = new FileTailor();
                Syslog.info(newImgPath);
                String prevfix = "commodityParticulars-";//缩略图前缀
                fileTailor.thumbnailImage(newImgPath, 300, 200, prevfix, false);
                String imgUrl = "/uploadImg/commodity" + "/commodityClass/" + commodityId + "/logo/" + DateUtil.getDay() + "/" + uuid + "." + suffix;
                Syslog.info("图片路径为：" + imgUrl);
                Record record = new Record().set("id", commodityId).set("logo", imgUrl);
                Db.update("shop_class", "id", record);
                map.put("code", "0");
                map.put("msg", "上传成功");
                Map data = new HashMap();
                data.put("src", imgUrl);
                data.put("title", "");
                map.put("data", data);

            }

        } catch (Exception e) {
            Syslog.error(e);
            map.put("code", "1");
            map.put("msg", e.toString());

        }
        return map;
    }


    public Map specialLogoImgUpload(List<UploadFile> uploadFiles, String id) {
        String projectPath = new GlobalParameter().projectPath;
        Map map = new HashMap();
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {
                UploadFile temp = uploadFiles.get(i);
                String fileName = temp.getFileName();
                /*copy图片到指定目录*/
                String uuid = UtilUUID.getUUID();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String slideshow = projectPath + "/uploadImg/specialLogoImg/" + DateUtil.getDay() + "/";
                String newImgPath = slideshow + uuid + "." + suffix;
                FileTailor.copyFile(temp.getUploadPath() + "/" + fileName, slideshow, newImgPath);
                /*压缩图片*/
                FileTailor fileTailor = new FileTailor();
                Syslog.info(newImgPath);
                String prevfix = "commodityParticulars-";//缩略图前缀
                fileTailor.thumbnailImage(newImgPath, 300, 200, prevfix, false);
                String imgUrl = "/uploadImg/specialLogoImg/" + DateUtil.getDay() + "/" + uuid + "." + suffix;
                Syslog.info("图片路径为：" + imgUrl);


                Record record = new Record().set("id", id).set("logo", imgUrl);
                Db.update("shop_special", "id", record);
                map.put("code", "0");
                map.put("msg", "上传成功");
                Map data = new HashMap();
                data.put("src", imgUrl);
                data.put("title", "");
                map.put("data", data);

            }

        } catch (Exception e) {
            Syslog.error(e);
            map.put("code", "1");
            map.put("msg", e.toString());

        }
        return map;
    }


    /**
     * 商品logo上传
     *
     * @param uploadFiles
     * @param commodityId
     * @return
     */
    public Map commodityLogoImgUpload(List<UploadFile> uploadFiles, String commodityId) {
        String projectPath = GlobalParameter.projectPath;
        // String projectPath = new GlobalParameter().projectPath;
        Map map = new HashMap();
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {
                UploadFile temp = uploadFiles.get(i);
                String fileName = temp.getFileName();
                /*copy图片到指定目录*/
                String uuid = UtilUUID.getUUID();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String slideshow = projectPath + "/uploadImg/commodity/" + commodityId + "/logo" + "/" + DateUtil.getDay() + "/";
                String newImgPath = slideshow + uuid + "." + suffix;
                FileTailor.copyFile(temp.getUploadPath() + "/" + fileName, slideshow, newImgPath);
                /*压缩图片*/
                FileTailor fileTailor = new FileTailor();
                Syslog.info(newImgPath);
                String prevfix = "commodityParticulars-";//缩略图前缀
                fileTailor.thumbnailImage(newImgPath, 300, 200, prevfix, false);
                String imgUrl = "/uploadImg/commodity" + "/" + commodityId + "/logo/" + DateUtil.getDay() + "/" + uuid + "." + suffix;
                Syslog.info("图片路径为：" + imgUrl);
                Record record = new Record().set("id", commodityId).set("logoPath", imgUrl);
                Db.update("applet_commodity", "id", record);
                map.put("code", "0");
                map.put("msg", "上传成功");
                Map data = new HashMap();
                data.put("src", imgUrl);
                data.put("title", "");
                map.put("data", data);

            }

        } catch (Exception e) {
            Syslog.error(e);
            map.put("code", "1");
            map.put("msg", e.toString());

        }
        return map;
    }

    /**
     * 商品长条图上传
     *
     * @param uploadFiles
     * @param commodityId
     * @return
     */
    public Map commodityImgUpload(List<UploadFile> uploadFiles, String commodityId) {
        String projectPath = GlobalParameter.projectPath;
        // String projectPath = new GlobalParameter().projectPath;
        Map map = new HashMap();
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {
                UploadFile temp = uploadFiles.get(i);
                String fileName = temp.getFileName();
                /*copy图片到指定目录*/
                String uuid = UtilUUID.getUUID();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                ///uploadImg/commodity/" + commodityId + "/logo" + "/" + DateUtil.getDay() + "/";
                String slideshow = projectPath + "/uploadImg/commodity/" + commodityId + "/" + DateUtil.getDay() + "/";
                String newImgPath = slideshow + uuid + "." + suffix;
                FileTailor.copyFile(temp.getUploadPath() + "/" + fileName, slideshow, newImgPath);
                /*压缩图片*/
                FileTailor fileTailor = new FileTailor();
                Syslog.info(newImgPath);
                String prevfix = "commodityParticulars-";//缩略图前缀
                fileTailor.thumbnailImage(newImgPath, 300, 200, prevfix, false);
                //String imgUrl = "/uploadImg/commodity" + "/" + commodityId + "/logo/" + DateUtil.getDay() + "/" + uuid + "." + suffix;
                String imgUrl = "/uploadImg/commodity" + "/" + commodityId + "/" + DateUtil.getDay() + "/" + uuid + "." + suffix;
                Syslog.info("图片路径为：" + imgUrl);
                Record record = new Record().set("id", commodityId).set("imgPath", imgUrl);
                Db.update("applet_commodity", "id", record);
                map.put("code", "0");
                map.put("msg", "上传成功");
                Map data = new HashMap();
                data.put("src", imgUrl);
                data.put("title", "");
                map.put("data", data);

            }

        } catch (Exception e) {
            Syslog.error(e);
            map.put("code", "1");
            map.put("msg", e.toString());

        }
        return map;
    }

    /**
     * 上传分享图片
     */


    public Map commodityShareImgUpload(List<UploadFile> uploadFiles, String commodityId) {
        //String projectPath = new GlobalParameter().projectPath;
        String projectPath = GlobalParameter.projectPath;
        Map map = new HashMap();
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {
                UploadFile temp = uploadFiles.get(i);
                String fileName = temp.getFileName();
                /*copy图片到指定目录*/
                String uuid = UtilUUID.getUUID();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String slideshow = projectPath + "/uploadImg/commodity/" + commodityId + "/" + DateUtil.getDay() + "/";
                String newImgPath = slideshow + uuid + "." + suffix;
                FileTailor.copyFile(temp.getUploadPath() + "/" + fileName, slideshow, newImgPath);
                /*压缩图片*/
                FileTailor fileTailor = new FileTailor();
                Syslog.info(newImgPath);
                String prevfix = "commodityParticulars-";//缩略图前缀
                fileTailor.thumbnailImage(newImgPath, 300, 200, prevfix, false);
                String imgUrl = "/uploadImg/commodity" + "/" + commodityId + "/" + DateUtil.getDay() + "/" + uuid + "." + suffix;
                Syslog.info("图片路径为：" + imgUrl);
                Record record = new Record().set("id", commodityId).set("imgPath", imgUrl);
                Db.update("applet_commodity", "id", record);
                map.put("code", "0");
                map.put("msg", "上传成功");
                Map data = new HashMap();
                data.put("src", imgUrl);
                data.put("title", "");
                map.put("data", data);

            }

        } catch (Exception e) {
            Syslog.error(e);
            map.put("code", "1");
            map.put("msg", e.toString());

        }
        return map;
    }

    /**
     * 首页轮播图上传
     */
    public Map homePageSlideshowImgUpload(List<UploadFile> uploadFiles, String commodityId) {
        String projectPath = new GlobalParameter().projectPath;
        Map map = new HashMap();
        try {
            for (int i = 0; i < uploadFiles.size(); i++) {
                UploadFile temp = uploadFiles.get(i);
                String fileName = temp.getFileName();
                /*copy图片到指定目录*/
                String uuid = UtilUUID.getUUID();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String slideshow = projectPath + "/uploadImg/homePageSlideshowImg/" + commodityId + "/";
                String newImgPath = slideshow + uuid + "." + suffix;
                FileTailor.copyFile(temp.getUploadPath() + "/" + fileName, slideshow, newImgPath);
                /*压缩图片*/
                FileTailor fileTailor = new FileTailor();
                Syslog.info(newImgPath);
                String prevfix = "homePageSlideshowImg-";//缩略图前缀
                fileTailor.thumbnailImage(newImgPath, 300, 200, prevfix, false);
                String imgUrl = "/uploadImg/homePageSlideshowImg/" + commodityId + "/" + uuid + "." + suffix;
                Syslog.info("图片路径为：" + imgUrl);
                map.put("code", "0");
                map.put("msg", "上传成功");
                Map data = new HashMap();
                data.put("src", imgUrl);
                data.put("title", "");
                map.put("data", data);
            }
        } catch (Exception e) {
            Syslog.error(e);
            map.put("code", "1");
            map.put("msg", e.toString());

        }
        return map;
    }


    /**
     * 根据商品ID查询商品图片
     */
    public List<Record> getCommodityImgPath(String commodityId, int type) {
        String sql = "SELECT *from shop_commodity_imgpath where commodityId='" + commodityId + "' and type=" + type + " order by number asc";
        List<Record> list = Db.find(sql);
        return list;
    }

    /**
     * 根据图片id查询出图片信息
     */
    public Record getImgsInfoById(String id) {
        String sql = "SELECT *from shop_commodity_imgpath where id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 保存图片序号
     */
    public ReturnData saveImgNumberService(String id, int number) {
        ReturnData returnData = new ReturnData();
        Record record = new Record().set("id", id).set("number", number);
        boolean up = Db.update("shop_commodity_imgpath", "id", record);
        if (up) {
            returnData.setMsg("保存成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("保存失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 根据图片记录id 删除图片文件
     */
    public ReturnData delImgByIdService(String id) {
        ReturnData returnData = new ReturnData();
        try {
            Record record = getImgsInfoById(id);
            String projectPath = new GlobalParameter().projectPath;
            String path = projectPath + record.getStr("path");
            int index = path.indexOf(id);
            String delPath = path.substring(1, index + id.length());
            FileUtil.delAllFile(delPath);
            FileUtil.delFolder(delPath);
            Db.delete("shop_commodity_imgpath", "id", record);
            returnData.setCode("000000");
            returnData.setMsg("删除成功");
        } catch (Exception e) {
            System.out.println("删除文件操作出错");
            e.printStackTrace();
            returnData.setCode("111111");
            returnData.setMsg("删除失败");
        }
        return returnData;
    }

    /**
     *
     */
    public ReturnData saveMessageContentService(String commodityId, String content) {
        ReturnData returnData = new ReturnData();
        String projectPath = new GlobalParameter().projectPath;
        String filePath = projectPath + "/commodity-message" + "/content-txt/" + "/" + commodityId + ".txt";
        File file = new File(projectPath + "/commodity-message" + "/content-txt/" + "/");
        if (!file.exists()) {
            file.mkdirs();
        }
        boolean write = FileUtil.writeToTxt(filePath, content);

        /*保存到详情路径*/
        Record record = new Record().set("description", filePath).set("id", commodityId);

        Db.update("ticket", "id", record);

        if (write) {
            returnData.setMsg("保存成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("保存失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     *
     */
    public ReturnData saveMessageParticulars(String commodityId, String content) {
        ReturnData returnData = new ReturnData();
        String projectPath = new GlobalParameter().projectPath;
        String filePath = projectPath + "/commodity-particulars" + "/content-txt/" + "/" + commodityId + ".txt";
        File file = new File(projectPath + "/commodity-particulars" + "/content-txt/" + "/");
        if (!file.exists()) {
            file.mkdirs();
        }
        boolean write = FileUtil.writeToTxt(filePath, content);
        if (write) {
            returnData.setMsg("保存成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("保存失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 获取轮播图
     *
     * @param page  当前页
     * @param limit 每页大小
     * @param type  类型 0 首页轮播图
     * @return
     */
    public List<Record> slideshowService(int page, int limit, int type) {
        String sql = "SELECT *from shop_slideshow where type=" + type + "  ORDER BY number ";
        PageUtil pageUtil = new PageUtil(page, limit, sql);

        List<Record> list = pageUtil.getList();

        return list;

    }

    /**
     * 保存轮播图
     */
    public ReturnData saveHomePageSlideshowInfoService(Map<String, String[]> map) {
        boolean sa = false;
        String id = map.get("id")[0];
        String imgPath = map.get("logo")[0];
        String number = map.get("number")[0];
        String shopId=map.get("shopId")[0];
        Record record = new Record().set("path", imgPath)
                .set("number", number).set("shopId",shopId).set("createTime",new Date());
        if ("".equals(id)) {//id 为空，新增记录
            record.set("id", UtilUUID.getUUID());
            sa = Db.save("slideshowimg", "id", record);
        } else {
            record.set("id", id);
            sa = Db.update("slideshowimg", "id", record);
        }
        ReturnData returnData = new ReturnData(sa);

        return returnData;
    }

    /**
     * 根据商品id获取商品信息
     */
    public Record getCommodityById(String id) {

        String sql = "SELECT *from shop_commodity where id='" + id + "'";

        Record record = Db.findFirst(sql);

        return record;
    }

    /**
     * 根据首页轮播图id删除记录
     */
    public ReturnData delHomePageSlideshowInfoService(String id) {

        boolean sa = false;

        Record record = new Record().set("id", id);

        sa = Db.delete("shop_slideshow", "id", record);

        ReturnData returnData = new ReturnData(sa);

        return returnData;
    }

    /**
     * 首页专区列表
     */
    public List<Record> specialListService() {

        String sql = "SELECT *from shop_special ORDER BY number";

        List<Record> list = Db.find(sql);

        return list;
    }

    /**
     * 保存专区信息
     */
    public ReturnData saveSpecialService(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String name = map.get("name")[0].trim();
        String logo = map.get("logo")[0];
        String number = map.get("number")[0].trim();
        Record record = new Record().set("name", name).set("logo", logo).set("number", number);
        if ("".equals(id)) {//id为空，新增分类
            record.set("id", UtilUUID.getUUID());
            boolean sa = Db.save("shop_special", "id", record);
            returnData = new ReturnData(sa);
        } else {
            record.set("id", id);
            boolean sa = Db.update("shop_special", "id", record);
            returnData = new ReturnData(sa);
        }
        return returnData;
    }

    /**
     * 删除专区
     */
    public ReturnData delSpecialService(String id) {

        Record record = new Record().set("id", id);

        boolean del = Db.delete("shop_special", "id", record);

        return new ReturnData(del);

    }

    /**
     * 专区商品
     */
    public PageUtil specialCommodityService(int page, int limit, String id) {

        String sql = "SELECT *from shop_special_commodity where specialId='" + id + "'";

        PageUtil pageUtil = new PageUtil(page, limit, sql);


        return pageUtil;
    }

    public ReturnData saveSpecialCommodityService(String specialId, String commoidtyId) {
        Record record = new Record().set("specialId", specialId);
        String delSql = "DELETE from shop_special_commodity where specialId='" + specialId
                + "' and commodityId='" + commoidtyId + "'";
        Db.delete(delSql);

        Record commodity = getCommodityById(commoidtyId);

        record.set("commodityId", commoidtyId).set("commodityName", commodity.getStr("name"))
                .set("commodityMoney", commodity.get("originalMoney")).set("commodityLogo", commodity.get("imgPath"))
                .set("commoditySales", commodity.get("sales"))
                .set("commodityBrowseCount", commodity.get("browseCount")).set("id", UtilUUID.getUUID());

        boolean sa = Db.save("shop_special_commodity", "id", record);

        return new ReturnData(sa);
    }

    /**
     * 类别id
     */
    public String getCommodityListByClassIdService(String classId) {

        String sql = "SELECT *from shop_commodity where classId='" + classId + "'";

        List<Record> list = Db.find(sql);

        String html = "<select disabled=\"disabled\" name=\"commodityId\" lay-verify=\"\" lay-search>\n";

        for (int i = 0; i < list.size(); i++) {
            Record temp = list.get(i);
            html += "  <option value=\"" + temp.getStr("id") + "\">" + temp.getStr("name") + "</option>\n";

        }
        html += "</select> \n";

        html += "   <div class=\"layui-form-select\">\n" +
                "\t<div class=\"layui-select-title\">\n";
        for (int i = 0; i < list.size(); i++) {
            Record temp = list.get(i);
            html += "<input type=\"text\" placeholder=\"请选择\" value=\"" + temp.getStr("name") + "\" class=\"layui-input\">\n";
        }
        html += "\t\t<i class=\"layui-edge\"></i>\n" +
                "\t</div>\n" +
                "\t<dl class=\"layui-anim layui-anim-upbit\">\n";
        for (int i = 0; i < list.size(); i++) {
            Record temp = list.get(i);
            html += "\t\t<dd lay-value=\"" + temp.getStr("id") + "\" class=\"\">" + temp.getStr("name") + "</dd>\n";

        }
        html += "\t</dl>\n" +
                "</div> ";


        return html;
    }

    /**
     * 删除专区商品
     */
    public ReturnData delSpecialCommodityService(String id) {

        Record record = new Record().set("id", id);

        boolean del = Db.delete("shop_special_commodity", "id", record);

        return new ReturnData(del);
    }

    /**
     * 平台统计
     */
    public Record statisticsService(String startDate, String endDate) {
        Record result = new Record();
        Record allOrder = orderStatisticsService(startDate, endDate);
        /*总金额*/
        double allOrderMoney = allOrder.getDouble("money");
        result.set("allOrderMoney", allOrderMoney);
        result.set("count", allOrder.getStr("number"));
        /*微信手续费*/
        double commissionMoney = new BigDecimal(allOrderMoney)
                .multiply(new BigDecimal(0.006)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        result.set("commissionMoney", commissionMoney);
        /*总返利金额*/
        Record allRebate = rebateStatisticsService(startDate, endDate);

        double allRebateMoney = allRebate.getDouble("money");
        result.set("allRebateMoney", allRebateMoney);
        /*充值记录*/
        Record rechargeRecord = rechargeStatisticsService(startDate, endDate);
        result.set("rechargeMoney", rechargeRecord.getDouble("money"));
        result.set("rechargeNumber", rechargeRecord.getDouble("number"));

        /*提现统计*/
        Record withdrawStatistics = withdrawStatisticsService(startDate, endDate);
        result.set("withdrawMoney", withdrawStatistics.getDouble("withdrawMoney"));//已提现金额
        result.set("applyMoney", withdrawStatistics.getDouble("applyMoney"));//申请金额
        /*剩余金额*/
        BigDecimal residueBigDecimal = new BigDecimal(allOrderMoney)
                .subtract(new BigDecimal(allRebateMoney));
        double residue = residueBigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

        result.set("residue", residue);

        return result;
    }


    /**
     * 订单统计
     */
    public Record orderStatisticsService() {
        /*订单数量*/
        String sql = "SELECT COUNT(*) as number,IFNULL(SUM(money),0.00) as money from shop_order where state!=0 and state!=8";
        Record record = Db.findFirst(sql);
        return record;
    }

    public Record orderStatisticsService(String startDate, String endDate) {
        /*订单数量*/
        String sql = "SELECT COUNT(*) as number,IFNULL(SUM(money),0.00)  as money from shop_order where DATE_FORMAT(createTime,'%Y-%m-%d') >='" + startDate
                + "' and DATE_FORMAT(createTime,'%Y-%m-%d') <='" + endDate + "'";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 返利统计
     */
    public Record rebateStatisticsService() {
        /*返利统计*/
        String sql = "SELECT COUNT(*) as number,IFNULL(SUM(money),0.00) as money from shop_member_account_info where code='004'";
        Record record = Db.findFirst(sql);
        return record;
    }

    public Record rebateStatisticsService(String startDate, String endDate) {
        /*返利统计*/
        String sql = "SELECT COUNT(*) as number,IFNULL(SUM(money),0.00) as money from shop_member_account_info where (code='004' or code='004') and DATE_FORMAT(createTime,'%Y-%m-%d')>='" + startDate
                + "' and DATE_FORMAT(createTime,'%Y-%m-%d')<='" + endDate + "' ";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 充值总金额
     */
    public Record rechargeStatisticsService(String startDate, String endDate) {
        /*充值金额*/
        String sql = "SELECT COUNT(*) as number,IFNULL(SUM(money),0.00) as money from shop_member_account_info WHERE code='001' and DATE_FORMAT(createTime,'%Y-%m-%d')>='" + startDate
                + "' and DATE_FORMAT(createTime,'%Y-%m-%d')<='" + endDate + "' ";
        Record record = Db.findFirst(sql);
        return record;

    }

    /**
     * 提现统计
     */
    public Record withdrawStatisticsService(String startDate, String endDate) {
        /*提现成功*/
        Record record = new Record();
        String sql = "SELECT COUNT(*) as number,IFNULL(SUM(money),0.00) as money from shop_withdraw_log WHERE state=1 and DATE_FORMAT(createTime,'%Y-%m-%d')>='" + startDate
                + "' and DATE_FORMAT(createTime,'%Y-%m-%d')<='" + endDate + "' ";
        Record withdrawRecord = Db.findFirst(sql);
        record.set("withdrawMoney", withdrawRecord.getDouble("money"));
        /*提现申请*/
        String applySql = "SELECT COUNT(*) as number,IFNULL(SUM(money),0.00) as money from shop_withdraw_log WHERE state=0 and DATE_FORMAT(createTime,'%Y-%m-%d')>='" + startDate
                + "' and DATE_FORMAT(createTime,'%Y-%m-%d')<='" + endDate + "' ";
        Record applyRecord = Db.findFirst(sql);
        record.set("applyMoney", applyRecord.getDouble("money"));
        return record;

    }

    /**
     * 提现记录
     */
    public PageUtil withdrawLogsService(int page, int limit, String key) {
        String sql = "SELECT *from shop_withdraw_log where state=0 or state=1 ORDER BY state";
        PageUtil pageUtil = new PageUtil(page, limit, sql);
        for (int i = 0; i < pageUtil.getList().size(); i++) {
            Record record = (Record) pageUtil.getList().get(i);
            int type = record.getInt("type");
            if (0 == type) {
                record.set("strType", "微信提现");
            } else if (1 == type) {
                record.set("strType", "支付宝提现");
            } else {
                record.set("strType", "银行卡提现");
            }

            int state = record.getInt("state");
            if (0 == state) {
                record.set("strState", "待审核");
            } else if (1 == state) {
                record.set("strState", "已打款");
            } else {
                record.set("strState", "已删除");
            }

        }
        return pageUtil;
    }

    /**
     * 提现状态
     */
    public ReturnData savewithdrawLogsStateService(String id, String state, String memberId,
                                                   double money) {
        Record record = new Record().set("id", id).set("state", state);
        boolean sa = Db.update("shop_withdraw_log", "id", record);
        if ("1".equals(state)) {//提现成功
            String sql = "UPDATE yx_member set accountMoney=(accountMoney -" + money + " ) where id='" + memberId + "'";
            int up = Db.update(sql);
            if (up != 1) {
                sa = false;
            }
        }
        if (sa == false) {
            throw new RuntimeException();
        }
        ReturnData returnData = new ReturnData(sa);
        return returnData;
    }



    /**
     * 商品列表
     */
    public PageUtil commodityListService(String page, String limit, String userId) {

        String shopId = this.findShop(userId);
        String sql = " SELECT c.* ,cc.name as className from  ticket c left join navigation cc on cc.id=c.classId  where c.shopId='" + shopId + "' ";
        String countSql = "select count(id) from ticket";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }

    //根据sys_userId查询shopId
    public String findShop(String userId) {
        String sql = "SELECT a.id FROM shop a LEFT JOIN sys_user b ON  a.sys_user_id=b.id WHERE b.id='" + userId + "'";
        return Db.queryStr(sql);
    }

    //根据sys_userId查询所属景区
    public String findSpot(String userId) {
        String sql = "SELECT b.spotName FROM sys_user b WHERE b.id='" + userId + "'";
        return Db.queryStr(sql);
    }
    /**
     * 根据商品Id获取对应的轮播图列表
     *
     * @param
     * @return
     */
    PageUtil getCommoditySlideShowByCommodityId(String commodityId) {
        String sql = "select * from shop_commodity_imgpath where commodityId ='" + commodityId + "'";
        String countSql = "select count(id) from shop_commodity_imgpath where commodityId ='" + commodityId + "'";
        PageUtil pageUtil = new PageUtil(1, 999, sql, countSql);
        return pageUtil;
    }

    public ReturnData saveCommodityService(Map<String, String[]> map) {

        boolean sa = false;

        String id = map.get("id")[0];

        String name = map.get("name")[0];

        String prize = map.get("prize")[0];

        String describe = map.get("describe")[0];

        String logoPath = map.get("logoPath")[0];

        String imgPath = map.get("imgPath")[0];

        String address = map.get("address")[0];

        Record record = new Record().set("name", name).set("prize", prize).set("describe", describe)
                .set("logoPath", logoPath).set("imgPath", imgPath).set("address", address);

        if ("".equals(id) || id == null) {//新增操作
            record.set("id", UtilUUID.getUUID());

            sa = save("applet_commodity", "id", record);
        } else {
            sa = Db.update("applet_commodity", "id", record);

        }
        return new ReturnData(sa);
    }

    /**
     * 保存拼字规则
     */
    public ReturnData saveRuleService(Map<String, String[]> map) {

        String discount0 = map.get("discount0")[0];
        String discount1 = map.get("discount1")[0];
        String discount2 = map.get("discount2")[0];
        String discount3 = map.get("discount3")[0];

        String number0 = map.get("number0")[0];
        String number1 = map.get("number1")[0];
        String number2 = map.get("number2")[0];
        String number3 = map.get("number3")[0];

        String startDate0 = map.get("startDate0")[0];
        String startDate1 = map.get("startDate1")[0];
        String startDate2 = map.get("startDate2")[0];
        String startDate3 = map.get("startDate3")[0];


        String endDate0 = map.get("endDate0")[0];
        String endDate1 = map.get("endDate1")[0];
        String endDate2 = map.get("endDate2")[0];
        String endDate3 = map.get("endDate3")[0];


        /*淘宝口令*/
        String command0 = map.get("command0")[0];
        String command1 = map.get("command1")[0];
        String command2 = map.get("command2")[0];
        String command3 = map.get("command3")[0];

        String gameId = map.get("gameId")[0];

        List<Record> ruleList = new ArrayList<>();

        Record rule0 = new Record().set("id", UtilUUID.getUUID()).set("mixSecond", 0).set("maxSecond", 3)
                .set("discount", discount0).set("gameId", gameId).set("startDate", startDate0)
                .set("endDate", endDate0).set("number", number0).set("command", command0);
        Record rule1 = new Record().set("id", UtilUUID.getUUID()).set("mixSecond", 4).set("maxSecond", 7)
                .set("discount", discount1).set("gameId", gameId).set("startDate", startDate1)
                .set("endDate", endDate1).set("number", number1).set("command", command1);

        Record rule2 = new Record().set("id", UtilUUID.getUUID()).set("mixSecond", 8).set("maxSecond", 10)
                .set("discount", discount2).set("gameId", gameId).set("startDate", startDate2)
                .set("endDate", endDate2).set("number", number2).set("command", command2);
        Record rule3 = new Record().set("id", UtilUUID.getUUID()).set("mixSecond", 10).set("maxSecond", 9999999)
                .set("discount", discount3).set("gameId", gameId).set("startDate", startDate3)
                .set("endDate", endDate3).set("number", number3).set("command", command3);

        ruleList.add(rule0);
        ruleList.add(rule1);
        ruleList.add(rule2);
        ruleList.add(rule3);

        String delSql = "DELETE  from applet_rule where gameId='" + gameId + "'";

        Db.delete(delSql);

        Db.batchSave("applet_rule", ruleList, ruleList.size());

        return new ReturnData(true);

    }

    /**
     * 查询规则
     */
    public Map getRuleService(String gameId) {

        Map resultMap = new HashMap();
        String sql = "select * from applet_rule where gameId='" + gameId + "' ORDER BY maxSecond";
        List<Record> list = Db.find(sql);

        if (list.size() == 4) {
            Record record0 = list.get(0);
            resultMap.put("discount0", record0.getStr("discount"));
            resultMap.put("number0", record0.getStr("number"));
            resultMap.put("startDate0", record0.getStr("startDate"));
            resultMap.put("endDate0", record0.getStr("endDate"));
            resultMap.put("command0", record0.getStr("command"));
            record0 = list.get(1);
            resultMap.put("discount1", record0.getStr("discount"));
            resultMap.put("number1", record0.getStr("number"));
            resultMap.put("startDate1", record0.getStr("startDate"));
            resultMap.put("endDate1", record0.getStr("endDate"));
            resultMap.put("command1", record0.getStr("command"));
            record0 = list.get(2);
            resultMap.put("discount2", record0.getStr("discount"));
            resultMap.put("number2", record0.getStr("number"));
            resultMap.put("startDate2", record0.getStr("startDate"));
            resultMap.put("endDate2", record0.getStr("endDate"));

            resultMap.put("command2", record0.getStr("command"));

            record0 = list.get(3);
            resultMap.put("discount3", record0.getStr("discount"));
            resultMap.put("number3", record0.getStr("number"));
            resultMap.put("startDate3", record0.getStr("startDate"));
            resultMap.put("endDate3", record0.getStr("endDate"));
            resultMap.put("command3", record0.getStr("command"));
        }

        return resultMap;
    }

    /**
     * 保存游戏
     */
    public ReturnData saveGameService(Map<String, String[]> map) {
        boolean sa = false;
        String id = map.get("id")[0];
        String name = map.get("name")[0];
        String type = map.get("type")[0];
        String shareTitle = map.get("shareTitle")[0];
        String shareImgPath = map.get("shareImgPath")[0];
        String dayNumber = map.get("dayNumber")[0];
        Record record = new Record().set("name", name).set("type", type).set("shareTitle", shareTitle)
                .set("shareImgPath", shareImgPath).set("dayNumber", dayNumber);

        if ("".equals(id) || id == null) {//新增游戏
            record.set("id", id).set("createTime", new Date());

            sa = Db.save("applet_game", "id", record);
        } else {

            sa = Db.update("applet_game", "id", record);
        }
        return new ReturnData(sa);
    }

    /**
     * 所有的游戏
     */
    public List<Record> commodityGameService(String commodityId) {

        String sql = "SELECT *from applet_game ORDER BY createTime desc ";
        List<Record> list = Db.find(sql);
        return list;
    }

    /**
     * 保存商品游戏关系
     */
    public ReturnData saveCommodityGameService(String commodityId, String gameId) {

        Record record = new Record().set("id", commodityId).set("gameId", gameId);

        boolean sa = Db.update("applet_commodity", "id", record);

        return new ReturnData(sa);

    }

    /**
     * 删除游戏
     */
    public ReturnData deleteGameService(String id) {
        ReturnData returnData = new ReturnData();
        returnData = new ReturnData();
        String sql = "DELETE FROM applet_game WHERE id = '" + id + "'";
        int delete = Db.delete(sql);
        if (delete == 1) {
            returnData.setMsg("删除成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("删除失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 保存游戏信息
     */
    public boolean saveGameService(Record game) {
        boolean sa = false;
        String id = game.getStr("id");
        if ("".equals(id) || id == null) {
            game.set("id", UtilUUID.getUUID());
            sa = Db.save("applet_game", "id", game);
        } else {
            sa = Db.update("applet_game", "id", game);
        }
        return sa;
    }

    /**
     * 查询游戏详情
     */
    public Record selectByIdService(String id) {
        String sql = "select * from applet_game where id = '" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }


    /**
     * 修改游戏信息
     */
    public ReturnData editGame(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        /*根据id获取游戏信息*/
        //String shareImgPath = map.get("shareImgPath")[0];
        Record game = selectByIdService(id);
        Iterator<Map.Entry<String, String[]>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String[]> next = iterator.next();
            if (!"file".equals(next.getKey())) {
                if ("shareImgPath".equals(next.getKey()) && next.getValue()[0] == "") {
                    continue;
                }
                game.set(next.getKey(), EmojiFilter.filterEmoji(next.getValue()[0]));
            }

        }
        boolean sa = saveGameService(game);
        if (sa) {
            returnData.setCode("000000");
            returnData.setMsg("更新信息成功");
            returnData.setData(game);
        } else {
            returnData.setCode("111111");
            returnData.setMsg("授权失败，请再次点击");
        }
        return returnData;
    }

    /**
     * 删除商品//@TODO此处仅删除了商品表
     */
    public ReturnData delCommodityService(String id) {
        ReturnData returnData = new ReturnData();
        String sql = "DELETE from ticket WHERE id = '" + id + "'";
        int delete = Db.delete(sql);
        if (delete == 1) {
            returnData.setMsg("删除成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("删除失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 保存商品信息
     */
    public boolean saveCommoditService(Record game) {
        boolean sa = false;
        String id = game.getStr("id");
        if ("".equals(id) || id == null) {
            game.set("id", UtilUUID.getUUID());
            sa = Db.save("applet_commodity", "id", game);
        } else {
            sa = Db.update("applet_commodity", "id", game);
        }
        return sa;
    }

    /**
     * 查询商品详情
     */
    public Record selectCommoditByIdService(String id) {
        String sql = "select c.*,cc.name as className,cc.parentId from ticketc left join commodity_class cc on c.classId =cc.id where c.id =?";
        Record record = Db.findFirst(sql, id);

        List<Record> classList0 = Db.find("select * from commodity_class where grade=0");
        record.set("grade0ClassList", classList0);

        return record;
    }

    /**
     * 修改商品信息
     */
    public ReturnData editCommodity(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        /*根据id获取游戏信息*/
        Record game = selectCommoditByIdService(id);
        Iterator<Map.Entry<String, String[]>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String[]> next = iterator.next();
            if (!"file".equals(next.getKey())) {
                if ("imgPath".equals(next.getKey()) && next.getValue()[0] == "") {
                    continue;
                }
                if ("logoPath".equals(next.getKey()) && next.getValue()[0] == "") {
                    continue;
                }
                game.set(next.getKey(), EmojiFilter.filterEmoji(next.getValue()[0]));
            }
        }
        boolean sa = saveCommoditService(game);
        if (sa) {
            returnData.setCode("000000");
            returnData.setMsg("更新信息成功");
            returnData.setData(game);
        } else {
            returnData.setCode("111111");
            returnData.setMsg("授权失败，请再次点击");
        }
        return returnData;
    }

    /**
     * 游戏规则设计回显
     *
     * @param gameId 游戏id
     * @return
     */
    public Map gameRuleShop(String gameId) {

        Map resultMap = new HashMap();
        String sql = "select * from applet_rule where gameId='" + gameId + "' ORDER BY maxSecond";
        List<Record> list = Db.find(sql);

        if (list.size() == 4) {
            Record record0 = list.get(0);
            resultMap.put("discount0", record0.getStr("discount"));
            resultMap.put("number0", record0.getStr("number"));
            resultMap.put("startDate0", record0.getStr("startDate"));
            resultMap.put("endDate0", record0.getStr("endDate"));
            resultMap.put("command0", record0.getStr("command"));
            record0 = list.get(1);
            resultMap.put("discount1", record0.getStr("discount"));
            resultMap.put("number1", record0.getStr("number"));
            resultMap.put("startDate1", record0.getStr("startDate"));
            resultMap.put("endDate1", record0.getStr("endDate"));
            resultMap.put("command1", record0.getStr("command"));
            record0 = list.get(2);
            resultMap.put("discount2", record0.getStr("discount"));
            resultMap.put("number2", record0.getStr("number"));
            resultMap.put("startDate2", record0.getStr("startDate"));
            resultMap.put("endDate2", record0.getStr("endDate"));

            resultMap.put("command2", record0.getStr("command"));

            record0 = list.get(3);
            resultMap.put("discount3", record0.getStr("discount"));
            resultMap.put("number3", record0.getStr("number"));
            resultMap.put("startDate3", record0.getStr("startDate"));
            resultMap.put("endDate3", record0.getStr("endDate"));
            resultMap.put("command3", record0.getStr("command"));
        }

        return resultMap;
    }

    /**
     * 根据parentId   获取二级商品分类
     *
     * @param parentId
     * @return
     */
    public List<Record> getClassTwoByParentId(String parentId) {
        List<Record> list = Db.find("select * from commodity_class where grade = 1 and parentId=?", parentId);
        return list;
    }

    /* 上传商品轮播图
     * @param map
     * @return
     */
    public ReturnData saveImpages(Map<String, String[]> map) {
        ReturnData data = new ReturnData();
        try {
            String images[] = map.get("imgPaths[]");
            String picInd[] = map.get("picInd[]");
            String imgPathId[] = map.get("imgPathId[]");
            String delIds = map.get("delIds")[0];
            String commodityId = map.get("commodityId")[0];
            String timestamp = String.valueOf(System.currentTimeMillis());
            if (images != null && !"".equals(images)) {

                for (int i = 0; i < images.length; i++) {
                    String number = picInd[i];
                    if ("".equals(number)) {
                        number = "0";
                    }
                    if (imgPathId[i] != null && !"".equals(imgPathId[i])) {
                        String sql = "update shop_commodity_imgpath set path='" + images[i] + "', number='" +
                                Integer.parseInt(number) + "'," +
                                "  timestamp ='" + timestamp + "'where id='" + imgPathId[i] + "'";
                        Db.update(sql);
                    } else {
                        Record record = new Record();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String date = sdf.format(new Date());
                        record.set("id", UtilUUID.getUUID()).set("path", images[i]).set("commodityId", commodityId)
                                .set("number", Integer.parseInt(number)).set("timestamp", timestamp);
                        Db.save("shop_commodity_imgpath", record);
                    }
                }
            }
            data.setCode("0");
            data.setMsg("保存成功！");
            if (delIds != null && !"".equals(delIds)) {
                String sql2 = "delete from shop_commodity_imgpath where id in (" + delIds + ")";
                Db.delete(sql2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            data.setCode("5");
            data.setMsg("服务器异常！");
        }
        return data;
    }

    //根据表名,sys_userId 查询商品对应分类集合
    public List<Record> findAllticketTypeBysysId(String tableName, String userId) {

        String sql = "  SELECT a.* FROM  " + tableName + " a  JOIN   shop b ON  a.shopId=b.id WHERE b.sys_user_id='" + userId + "'";
        List<Record> list = new ArrayList<>();
        try {
            list = Db.find(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 商品发布
     *
     * @param map
     * @return
     */
    public ReturnData saveCommodityService(Map<String, String[]> map, String userId) {

        boolean sa = true;
        String ticketId = map.get("id")[0];   //商品id，如果不为空，说明是修改的逻辑
        String id = UtilUUID.getUUID().substring(18); //商品Id
        String name = map.get("name")[0]; //商品名称
        String originalMoney = map.get("originalMoney")[0];//商品原价
        String spotName=map.get("spotName")[0]; //所属景区名称
        String money = map.get("money")[0]; //商品现价
        Date date = new Date();//商品创建时间
        String description = map.get("description")[0];  //商品描述
        String inventory = map.get("inventory")[0]; //商品库存

        String state = map.get("state")[0]; //商品状态
        String classId = map.get("classId")[0];  //商品类别
        String personType=map.get("personType")[0]; //人员类别
        String snapStartTime=null;
        if(map.get("snapTime")!=null) {
            snapStartTime = map.get("snapTime")[0]; //商品抢购结束时间
        }
        String endTime=map.get("endTime")[0];
        String salNum = map.get("salNum")[0]; //销量
        String oneprofits = map.get("oneprofits")[0]; //一级分销利润

        String twoprofits = map.get("twoprofits")[0]; //二级级分销利润

        String isNeedAddress=map.get("isNeedAddress")[0]; //收货地址是否需要
        String isNeedIdnumber=map.get("isNeedIdnumber")[0]; //说我那份证号是否需要
        String writeoff=map.get("writeoff")[0]; //是否发送核销短信
        String[] ticketlogos=map.get("ticketlogo");     //商品外部展示图
        String ticketlogo="";
        if(ticketlogos!=null){
            ticketlogo=ticketlogos[0];
        }
        String shopId = this.findShop(userId);
        try {
            //保存商品规格
            String[] manIds = map.get("manIds");   //人员类型id
            String[] ticket_types = map.get("ticket_types");      //票种id
            String[] mothods = map.get("method");    //取票方式id
            List<Record> ticketSkuList = new ArrayList<>();  //商品规格集合
            for (int m = 0; m < manIds.length; m++) {
                Record sku = new Record(); //商品单个规格
                String key = AES.AESEncode(id + "|" + manIds[m] + "|" + ticket_types[m] + "|" + mothods[m]);
                String money1 = map.get("paioMoney")[m];  //票价
                Record ticket_money = new Record();
                sku.set("money", money1).set("ticket_person_typeId", manIds[m]).set("ticket_typeId", ticket_types[m]).set("ticket_methodId", mothods[m]);
                ticketSkuList.add(sku);
                ticket_money.set("key", key).set("money", money1).set("commodityId", id);
                if ("".equals(ticketId)) {

                    Db.save("ticket_money", ticket_money);
                } else {
                    String sql = "SELECT * FROM ticket_money WHERE commodityId='" + ticketId + "'";
                    List<Record> moneyList = Db.find(sql);
                    if (moneyList.size() > 0) {
                        //先删除
                        for (int b = 0; b < moneyList.size(); b++) {
                            Db.delete("ticket_money", "key", moneyList.get(b));
                        }

                    }
                    Db.save("ticket_money",  ticket_money);
                }
            }
            String goodDescImgs = map.get("goodDescImgs")[0];//轮播图路径组合字符串
            Gson gson2 = new Gson();
            String ticketSku = gson2.toJson(ticketSkuList);
            Record ticket = new Record();
            //添加时候
            if ("".equals(ticketId)) {
                ticket.set("id", id).set("name", name).set("originalMoney", originalMoney).set("money", money).set("createTime", date).set("description", description).set("inventory", inventory)
                        .set("state", state).set("classId", classId).set("salNum", Integer.parseInt(salNum)).set("shopId", shopId).set("personType",personType)
                        .set("ticketSku", ticketSku).set("imgPath", goodDescImgs).set("oneprofits", oneprofits).set("isNeedAddress",isNeedAddress).set("endTime",endTime)
                        .set("isNeedIdnumber",isNeedIdnumber).set("twoprofits",twoprofits).set("logo",ticketlogo).set("writeoff",writeoff).set("spotName",spotName);
                if(snapStartTime!=null && !"".equals(snapStartTime)){
                    ticket.set("snapTime", snapStartTime);
                }else {
                    ticket.set("snapTime", null);
                }
                //保存商品
                Db.save("ticket", ticket);

            } else {//修改时候
                ticket.set("id", ticketId).set("name", name).set("originalMoney", originalMoney).set("money", money).set("createTime", date).set("description", description).set("inventory", inventory)
                        .set("state", state).set("classId", classId).set("salNum", Integer.parseInt(salNum)).set("shopId", shopId).set("personType",personType)
                        .set("ticketSku", ticketSku).set("imgPath", goodDescImgs).set("oneprofits", oneprofits).set("isNeedAddress",isNeedAddress).set("endTime",endTime)
                        .set("isNeedIdnumber",isNeedIdnumber).set("twoprofits",twoprofits).set("logo",ticketlogo).set("writeoff",writeoff).set("spotName",spotName);
                if(snapStartTime!=null && !"".equals(snapStartTime)){
                    ticket.set("snapTime", snapStartTime);
                }else {
                    ticket.set("snapTime", null);
                }
                Db.update("ticket", ticket);
            }


            //保存商品轮播图

            //添加时候
            if ("".equals(ticketId)) {
                if (goodDescImgs != null) {
                    String[] imgPath = goodDescImgs.split("\\|");
                    if (imgPath.length > 0) {
                        for (int i = 0; i < imgPath.length; i++) {
                            Record record = new Record();
                            record.set("id", UtilUUID.getUUID()).set("path", imgPath[i]).set("commodityId", id)
                                    .set("number", Integer.parseInt("0")).set("timestamp", String.valueOf(System.currentTimeMillis()));
                            Db.save("shop_commodity_imgpath", record);
                        }

                    }
                }
            } else {
                //先删除之前的轮播图
                String sql = "SELECT * FROM shop_commodity_imgpath  WHERE commodityId='" + ticketId + "'";
                List<Record> list = Db.find(sql);
                if (list.size() > 0) {
                    for (int a = 0; a < list.size(); a++) {
                        Db.delete("shop_commodity_imgpath", list.get(a));
                    }
                }
                String[] imgPath = goodDescImgs.split("\\|");
                if (imgPath.length > 0) {
                    for (int i = 0; i < imgPath.length; i++) {
                        Record record = new Record();
                        record.set("id", UtilUUID.getUUID()).set("path", imgPath[i]).set("commodityId", ticketId)
                                .set("number", Integer.parseInt("0")).set("timestamp", String.valueOf(System.currentTimeMillis()));
                        Db.save("shop_commodity_imgpath", record);
                    }

                }
            }


        } catch (Exception e) {
            sa = false;
            e.printStackTrace();
        }
        return new ReturnData(sa);
    }

    //根据id查询商品详情
    public Record findTicketdetail(String id) {
        String sql = "SELECT a.*,b.`name` AS className FROM ticket a LEFT JOIN navigation b ON a.classId=b.id  WHERE a.id='"+id+"'";
        Record record = Db.findFirst(sql);
        String sku = record.get("ticketSku");
        Gson gson2 = new Gson();
        List<Record> skuList = gson2.fromJson(sku, new TypeToken<List<Record>>() {
        }.getType());
        record.set("sku", skuList);
        return record;
    }

    //添加商户
    public ReturnData addShop(Map<String, String[]> map) {

        ReturnData returnData = new ReturnData();

        String id=map.get("id")[0];

        String merchant_name = map.get("merchant_name")[0]; //商户名

        String phone = map.get("phone")[0];  //手机号

        String per_commission = map.get("per_commission")[0]; //每单提成

        String adress = map.get("adress")[0];    //商户地址

        String charges_type = map.get("charges_type")[0];//收费类型

        String enterTime = map.get("enterTime")[0]; //加入时间

        String endTime = map.get("endTime")[0];  //到期时间

        String synopsis = map.get("synopsis")[0];    //公司简介

        String serviceTel = map.get("serviceTel")[0];//客服电话

        String emal = map.get("email")[0]; //邮箱

        String workingTime = map.get("workingTime")[0];  //工作时间

        Record shop = new Record();
        try {

            if ("".equals(id) || id==null){//新增商户
                id = UtilUUID.getUUID(); //商户id
                //给商户添加基本用户表
                Record sys_user = new Record();
                String userId = UtilUUID.getUUID();
                String salt = UtilUUID.getOrderIdByUUId();
                String password = MD5.md5(phone + salt + "123456");

                sys_user.set("id", userId).set("userCode", phone).set("userName", merchant_name).set("password", password).set("locked", "0").set("type", "2")
                        .set("salt", salt).set("shopId", id).set("adminUserId", 1).set("phone", phone);
                Db.save("sys_user", "id", sys_user);
                shop.set("id", id).set("merchant_name", merchant_name).set("phone", phone).set("per_commission", per_commission).set("adress", adress)
                        .set("charges_type", charges_type).set("enterTime", enterTime).set("order_number", 0)
                        .set("endTime", endTime)
                        .set("synopsis", synopsis).set("serviceTel", serviceTel).set("emal", emal).set("workingTime", workingTime).set("sys_user_id", userId);
                //保存商户
                Db.save("shop", shop);

                //添加角色
                String rolesql = "SELECT * FROM sys_role  WHERE name='代理商'";
                Record role = Db.findFirst(rolesql);
                Record newROLE = new Record(); //用户角色中间表
                newROLE.set("id", UtilUUID.getUUID()).set("sys_user_id", userId).set("sys_role_id", role.get("id"));
                Db.save("sys_user_role", newROLE);
                returnData.setCode("0");
                returnData.setResult(true);
            }else {//修改商户
                shop.set("id", id).set("merchant_name", merchant_name).set("phone", phone).set("per_commission", per_commission).set("adress", adress)
                        .set("charges_type", charges_type).set("enterTime", enterTime).set("order_number", 0)
                        .set("endTime", endTime)
                        .set("synopsis", synopsis).set("serviceTel", serviceTel).set("emal", emal).set("workingTime", workingTime);
                //保存商户
                Db.update("shop","id", shop);
            }

        } catch (Exception e) {
            e.printStackTrace();
            returnData.setCode("1");
            returnData.setResult(false);
        }
        return returnData;
    }


    /**
     * 系统参数设置
     */
    public PageUtil showChanshu(String page, String limit) {
        String sql = "SELECT * FROM sys_config";
        String countSql = "SELECT COUNT(*) FROM sys_config";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }

    /**
     * 修改系统参数
     */
    public ReturnData updaCanshu(String element, String value) {
        ReturnData returnData = new ReturnData();
        String sql = "UPDATE sys_config SET `value`='" + value + "' where element='" + element + "'";
        int i = Db.update(sql);
        if (i > 0) {
            returnData.setResult(true);
            returnData.setCode("000000");
        } else {
            returnData.setResult(false);
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 修改显示
     */
    public ReturnData showUpda(String element) {
        String value = Db.queryStr("select `VALUE` from sys_config where element=?", element);
        ReturnData rd = new ReturnData(true);
        rd.setData(value);
        return rd;
    }

    /**
     * 票种管理
     */
    public PageUtil ticket(String page, String limit,String shopId) {
        String sql = "SELECT * from ticket_type WHERE shopId='"+shopId+"'";
        String coutSql = "SELECT count(*) from ticket_type WHERE shopId='"+shopId+"'";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, coutSql);
        return pageUtil;
    }

    /**
     * 删除票种
     */
    public ReturnData delTicket(String id) {
        ReturnData returnData = new ReturnData();
        String sql = "DELETE from ticket_type where id='" + id + "'";
        int i = Db.delete(sql);
        if (i > 0) {
            returnData.setResult(true);
            returnData.setCode("000000");
        } else {
            returnData.setResult(false);
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 修改添加票种
     */
    public ReturnData updaSave(Map<String, String[]> map, String shopId) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String typeName = map.get("typeName")[0];
        String number = map.get("number")[0];
        boolean result = false;
        if (id != null && !id.isEmpty()) {
            result = Db.update("ticket_type", "id", new Record().set("id", id)
                    .set("typeName", typeName).set("number", number).set("shopId", shopId));
        }
        if (id == null || "".equals(id)) {
            result = save("ticket_type", new Record().set("id", UtilUUID.getUUID()).set("typeName", typeName)
                    .set("number", number).set("shopId", shopId));
        }
        returnData.setResult(result);
        if (result) {
            returnData.setMsg("创建成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("创建失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 票种编辑显示
     */
    public Record showPiao(String id) {
        String sql = "SELECT * from ticket_type where id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 人员类型设定
     */
    public PageUtil ticketRen(String page, String limit,String shopId) {
        String sql = "SELECT * FROM ticket_person_type where shopId='"+shopId+"'";
        String countSql = "SELECT count(*) FROM ticket_person_type where shopId='"+shopId+"' ";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }

    /**
     * 删除人员类型设定
     */
    public ReturnData delTicketRenService(String id) {
        ReturnData returnData = new ReturnData();
        String sql = "DELETE FROM ticket_person_type where id='" + id + "'";
        int i = Db.delete(sql);
        if (i > 0) {
            returnData.setResult(true);
            returnData.setCode("000000");
        } else {
            returnData.setResult(false);
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 修改添加
     */
    public ReturnData updaSavepersontypeService(Map<String, String[]> map,String shopId) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String personType = map.get("personType")[0];
        String number = map.get("number")[0];
        boolean result = false;
        if (id != null || id.isEmpty()) {
            result = Db.update("ticket_person_type", "id", new Record().set("id", id)
                    .set("personType", personType).set("number", number).set("shopId",shopId));
        }
        if (id == null || "".equals(id)) {
            result = save("ticket_person_type", new Record().set("id", UtilUUID.getUUID())
                    .set("personType", personType).set("number", number).set("shopId",shopId));
        }
        returnData.setResult(result);
        if (result) {
            returnData.setMsg("创建成功");
            returnData.setCode("000000");
        } else {
            returnData.setMsg("创建失败");
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 修改人员显示
     */
    public Record updapersontypeService(String id) {
        String sql = "SELECT * from ticket_person_type where id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }

    /**
     * 专区表
     */
    public PageUtil selePrefectureService(String page, String limit,String shopId) {
        String sql = "SELECT * from ticket_prefecture where shopId='"+shopId+"' order by number ";
        String countSql = "SELECT count(*) from ticket_prefecture where shopId='"+shopId+"' ";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }
    /**
     * 专区商品列表
     */
    public PageUtil prefectureCommodityService(String page, String limit,String prefectureId,String shopId){

        String sql="SELECT\n" +
                "\tpt.id,\n" +
                "\tt.`name`,\n" +
                "\tt.id AS ticketId,pt.prefectureId\n" +
                "FROM\n" +
                "\tprefecture_ticket pt\n" +
                "RIGHT JOIN ticket t ON pt.ticketId = t.id\n" +
                "WHERE\n" +
                "\t t.shopId='"+shopId+"' ";

        String countSql="SELECT\n" +
                " count(*) " +
                "FROM\n" +
                "\tprefecture_ticket pt\n" +
                "RIGHT JOIN ticket t ON pt.ticketId = t.id\n" +
                "WHERE\n" +
                "\t t.shopId='"+shopId+"' ";

        PageUtil pageUtil=new PageUtil(Integer.parseInt(page),Integer.parseInt(limit),sql,countSql);



        return pageUtil;

    }

    public ReturnData upPrefectureCommodityService(String prefectureId,String ticketId,String state){


        boolean sa=false;

        if ("true".equals(state)){

            Record record=new Record().set("prefectureId",prefectureId).set("ticketId",ticketId)
                    .set("id",UtilUUID.getUUID());

            sa=Db.save("prefecture_ticket","id",record);

        }else {

            String sql="DELETE from prefecture_ticket where prefectureId='"+prefectureId
                    +"' and ticketId='"+ticketId+"'";
            int up=Db.update(sql);

            if (up>0){

                sa=true;
            }
        }

        ReturnData returnData=new ReturnData(sa);

        return returnData;
    }

    /**
     * 删除专区
     */
    public ReturnData delPrefectureService(String id) {
        ReturnData returnData = new ReturnData();
        String sql = "DELETE FROM ticket_prefecture where id='" + id + "'";
        int i = Db.delete(sql);
        if (i > 0) {
            returnData.setCode("000000");
            returnData.setResult(true);
        } else {
            returnData.setCode("111111");
            returnData.setResult(false);
        }
        return returnData;
    }

    /**
     * 修改添加专区表
     */
    public ReturnData updaSavePrefectureService(Map<String , String[]> map,String shopId) {

        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String title = map.get("title")[0];
        String number = map.get("number")[0];
        String logo=map.get("logo")[0];
        boolean result = false;

        if (id == null || "".equals(id)) {
            result = save("ticket_prefecture", new Record().set("id", UtilUUID.getUUID()).set("title", title)
                    .set("number", number).set("shopId", shopId).set("logo",logo));

        }else {

            result = Db.update("ticket_prefecture", "id", new Record().set("id", id).set("title", title)
                    .set("number", number).set("shopId", shopId).set("logo",logo));
        }
        returnData.setResult(result);
        return returnData;

    }

    /**
     * 修改专区显示
     */
    public Record updaPrefectureService(String id) {
        String sql = "select * from ticket_prefecture where id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }


    //商户列表
    public PageUtil allshop(String page, String limit) {
        String sql = "SELECT * FROM shop ";
        String countSql="SELECT count(*) FROM shop";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page),Integer.parseInt(limit),sql,countSql);
        return pageUtil;
    }


    public ReturnData settingWithdrawerService(String shopId){


        return null;
    }


    /**
     * 添加优惠券
     * @param map
     * @param userId
     * @return
     */
    public ReturnData addCoupon(Map<String, String[]> map, String userId) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];
        String name = map.get("name")[0];//名称
        String mixMoney = map.get("mixMoney")[0]; //最低消费
        String money = map.get("money")[0];//优惠金额
        String price = map.get("price")[0];  //卖价
        String startTime = map.get("startTime")[0];  //开始时间
        String endTime = map.get("endTime")[0]; //结束时间
        String giveType = map.get("giveType")[0];  //类型
        int state = 0;  //状态默认可用
        String remark = map.get("remark")[0]; //备注信息
        Record record = new Record();
        String shopId = this.findShop(userId);
        try {
            record.set("name", name).set("mixMoney", mixMoney).set("money", money).set("price", price).set("startTime", startTime)
                    .set("endTime", endTime).set("giveType", giveType).set("state", state).set("remark", remark).set("shopId", shopId).set("createTime", new Date());
            if ("".equals(id)) {
                Db.save("yx_coupon", record);
            } else {
                record.set("id", id);
                Db.update("yx_coupon", record);
            }

            returnData.setCode("0");
        } catch (Exception e) {
            e.printStackTrace();
            returnData.setCode("1");
        }
        return returnData;
    }

    //优惠券详情
    public Record findCoupon(String id) {
        String sql = "SELECT * FROM yx_coupon WHERE id='" + id + "'";
        Record record = Db.findFirst(sql);
        return record;
    }

    //商户下的优惠卷
    public List<Record> allcoupon(String shopId) {
        String sql = "SELECT * FROM yx_coupon WHERE shopId='" + shopId + "'";
        List<Record> list = Db.find(sql);
        return list;
    }

    //商品关联优惠券
    public ReturnData shoplinkCoupon(Map<String, String[]> map, String shopId) {
        ReturnData returnData = new ReturnData();
        String id = map.get("id")[0];//商品id
        String couponId = map.get("couponId")[0]; //优惠券id
        Record ticket_coupon = new Record();//商品优惠券关联
        try {
            ticket_coupon.set("id", UtilUUID.getUUID()).set("couponId", couponId).set("ticketId", id).set("shopId", shopId).set("createTime", new Date());
            Db.save("ticket_coupon", ticket_coupon);
            returnData.setCode("0");
        } catch (Exception e) {
            e.printStackTrace();
            returnData.setCode("1");
        }
        return returnData;
    }

    //生成待支付订单
    public ReturnData Generateorder(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String ticketId = map.get("ticketId")[0]; //商品Id
        String memberId = map.get("memberId")[0]; //会员Id
        String number = map.get("number")[0]; //商品数量
        String money = map.get("money")[0]; //商品价格
        Record ticket = this.findTicketdetail(ticketId); //商品详情
        String shopId = ticket.get("shopId"); //商户Id
        Record yx_order = new Record(); //新建订单
        try {
            yx_order.set("commodityId", ticketId).set("money", money).set("memberId", memberId).set("number", number).set("shopId", shopId).set("id", UtilUUID.getUUID());
            Db.save("yx_order", yx_order);
            returnData.setCode("0");
            returnData.setMsg("待支付订单创建成功");

        } catch (Exception e) {
            e.printStackTrace();
            returnData.setCode("1");
            returnData.setMsg("信息异常");
        }
        return returnData;
    }


    //查询商品规格对应的价格 跳转到付款页面
    public ReturnData buyGood(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String ticket_person_typeId = map.get("ticket_person_typeId")[0]; //人员类型Id
        String ticket_typeId = map.get("ticket_type")[0];//票种Id
        String ticket_methodId = map.get("ticket_method")[0]; //取票方式Id
        String ticketId = map.get("ticketId")[0]; //商品Id
        Record returnRecord = new Record();   //返回信息
        String addressSql = "SELECT * FROM yx_member_address WHERE memberId='fa1cdc0a089d4c3b809a246b7ae5bd96'"; //送货地址
        Record address = Db.findFirst(addressSql);
        returnRecord.set("address", address);
        returnRecord.set("number", 2);
        try {
            Record ticket = this.findTicketdetail(ticketId); //商品详情
            List<Record> list = ticket.get("sku");
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Record record = list.get(i);//商品规格
                    //根据 门票id+门票类型id+票种id+取票Id 查询money
                    if (ticket_methodId.equals(record.get("ticket_methodId")) && ticket_person_typeId.equals(record.get("ticket_person_typeId"))
                            && ticket_typeId.equals(record.get(ticket_typeId))) {
                        returnRecord.set("money", record.get("money"));
                    }
                }
            }
            returnData.setData(returnRecord);
            returnData.setCode("0");
            returnData.setMsg("待支付订单创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnData.setCode("1");
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    //查看可用优惠券
    public ReturnData Viewavailablecoupons(Map<String, String[]> map) {
        ReturnData returnData = new ReturnData();
        String memberId = map.get("memberId")[0]; //会员Id
        String ticketId = map.get("ticketId")[0]; //商品Id
        //根据商品id查询shopId
        Record ticket = this.findTicketdetail(ticketId); //商品详情
        String shopId = ticket.get("shopId"); //商户Id
        List<Record> coupons = new ArrayList<>();
        try {
            //根据shopId和memberId查询可用的优惠券
            String sql = "SELECT a.* FROM yx_coupon_card a where a.memberId='"+memberId+"' and a.shopId='"+shopId+"' and a.state='0'";
            coupons = Db.find(sql);
            if (coupons.size() > 0) {
                for (int i = 0; i < coupons.size(); i++) {
                    String sqlDetail = "SELECT * FROM yx_coupon a WHERE id='17'";
                    Record record = Db.findFirst(sqlDetail);
                    coupons.get(i).set("Detail", record);
                    //判断优惠券是否过期
                    Date date = coupons.get(i).get("endTime");
                    Date newDate = new Date();

                    if (newDate.getTime() > date.getTime()) {//优惠券已过期
                        coupons.remove(i);

                        continue;

                    }
                    //判断是否满足优惠券的使用金额
                    int money = ticket.get("money"); //商品价格
                    String couMoney = record.get("mixMoney");//优惠券最低消费
                    if (money < Double.parseDouble(couMoney)) {
                        coupons.remove(i);
                        continue;
                    }
                }
            }
            returnData.setData(coupons);
            returnData.setCode("0");
            returnData.setMsg("待支付订单创建成功");

        } catch (Exception e) {
            e.printStackTrace();
            returnData.setCode("1");
            returnData.setMsg("信息异常");
        }
        return returnData;
    }


    public  PageUtil navigationService(String page,String limit,String shopId){
        String sql="SELECT * from navigation where shopId='"+shopId+"'";
        String countSql="SELECT count(*) from navigation where shopId='"+shopId+"'";
        PageUtil pageUtil=new PageUtil(Integer.parseInt(page),Integer.parseInt(limit),sql,countSql);
        return pageUtil;
    }

    /**
     * 查询轮播图
     * @param shopId
     * @return
     */
    public List<Record> slideShowListService(String shopId){

        String sql = "SELECT * from slideshowimg where shopId='"+shopId+"' ";

        List<Record> slideShowList=Db.find(sql);

        return slideShowList;
    }
    /**
     * 删除轮播图
     * @param id
     * @return
     */
    public ReturnData deleTeService(String id){
        ReturnData returnData = new ReturnData();
        String sql = "DELETE FROM slideshowimg where id='"+id+"'";
        int flag=Db.delete(sql);
        if (flag>0){
            returnData.setCode("000000");
            returnData.setMsg("删除成功");
        }else {
            returnData.setCode("111111");
            returnData.setMsg("删除失败");
        }
        return  returnData;
    }
    /**
     * 删除商品
     */
    public ReturnData delNavigationService(String id){
        ReturnData returnData=new ReturnData();
        String sql="DELETE from navigation where id='"+id+"'";
        int i=Db.delete(sql);
        if(i>0){
            returnData.setResult(true);
            returnData.setCode("000000");
        }else{
            returnData.setResult(false);
            returnData.setCode("111111");
        }
        return returnData;
    }
    /**
     * 商品一级分类
     * @return
     */
    public List<Record> firstClass(String shopId){
        String sql="SELECT *from navigation where grade=0 AND shopId='"+shopId+"' ORDER BY number";
        List<Record> list=Db.find(sql);
        return list;
    }

    /**
     * 根据一级分类Id查询下面的二级分类
     * @param parentId
     * @return
     */
    public List<Record> twolevelClass(String parentId){
        String sql="SELECT *from navigation where grade='1' AND parentId='"+parentId+"' ORDER BY number  ";
        List<Record> list=Db.find(sql);
        return list;
    }

    /**
     * 商品分类详情
     * @param id
     * @return
     */
    public Record ClassDetail(String id){
        String sql="SELECT *from navigation where  id='"+id+"'   ";
        Record record=Db.findFirst(sql);
        return record;
    }
    /**
     * 查询微信配置
     * @param
     * @return
     */
    public  Record weChatcon(String shopId){
        Record record = new Record();
        String sql = "SELECT * FROM weixin_public_account_info where shopId='"+shopId+"' ";
        record = Db.findFirst(sql);
        if(record==null){
            Record record1=new Record();
            //新商户添加小程序配置
            record1.set("shopId",shopId).set("type","1");
            Db.save("weixin_public_account_info","id",record1);

            Record weixinRecord=new Record();
            weixinRecord.set("shopId",shopId).set("appId","wxb908a5e23c62afd4").set("appSecret", "a7eb6b72973b801df4549f1159561776").set("mchId","1412185402")
                    .set("payKey","de28ffc5b3e04fc1bd72b0d3b9c0c40a").set("domain","www.keleziyouxing.com").set("type","0");

            Db.save("weixin_public_account_info","id",weixinRecord);

            record=record1;

        }
        return record;
    }


    /**
     * 添加修改微信配置
     * @param map
     * @return
     */
    public ReturnData addOnWeChat(Map<String,String[]>map){
        boolean as = false;
        String id=map.get("id")[0];
        String shopId = map.get("shopId")[0];
        String appId = map.get("appId")[0];
        String appSecret = map.get("appSecret")[0];
        String mchId = map.get("mchId")[0];
        String payKey = map.get("payKey")[0];
//        String originalId = map.get("originalId")[0];
        String domain = map.get("domain")[0];
//        String name = map.get("name")[0];
//        String type = map.get("type")[0];
        Record record = new Record();
        record.set("shopId",shopId).set("appId",appId).set("appSecret",appSecret).set("mchId",mchId)
                .set("payKey",payKey).set("domain",domain).set("id",id)
                .set("createTime",new Date());


        as = Db.update("weixin_public_account_info","id",record);


        ReturnData returnData = new ReturnData(as);
        return returnData;
    }
    /**
     * 查询关联优惠卷
     */
    public Record couponServie(String id){
        String sql="SELECT tc.id as ticketCouponId , yxc.*, tc.* FROM yx_coupon yxc RIGHT JOIN ticket_coupon tc ON yxc.id = tc.couponId WHERE tc.ticketId = '"+id+"'";
        Record record=Db.findFirst(sql);
        return record;
    }

    /**
     * 取消关联
     */
    public ReturnData closeCouponServie(String id){
        ReturnData returnData=new ReturnData();
        String sql="DELETE from ticket_coupon WHERE id='"+id+"'";
        int i=Db.delete(sql);
        if(i>0){
            returnData.setResult(true);
            returnData.setCode("000000");
        }else{
            returnData.setResult(false);
            returnData.setCode("111111");
        }
        return returnData;
    }

    /**
     * 查询关联优惠卷
     * @param page
     * @param limit
     * @param id
     * @return
     */
    public PageUtil seleCouponService(String page,String limit,String id){
        String sql="SELECT * from yx_coupon LEFT JOIN ticket_coupon on yx_coupon.id=ticket_coupon.couponId where ticket_coupon.ticketId='"+id+"'";
        String countSql="SELECT count(*) from yx_coupon LEFT JOIN ticket_coupon on yx_coupon.id=ticket_coupon.couponId where ticket_coupon.ticketId='"+id+"'";
        PageUtil pageUtil=new PageUtil(Integer.parseInt(page),Integer.parseInt(limit),sql,countSql);
        return pageUtil;
    }
    /**
     * 修改加盟商
     */
    public ReturnData updaShop(Map<String ,String []> map){
        ReturnData returnData=new ReturnData();
        String id=map.get("id")[0];//ID
        String merchant_name=map.get("merchant_name")[0];//姓名
        String phone=map.get("phone")[0];//电话
        String adress=map.get("adress")[0];//地址
        String per_commission=map.get("per_commission")[0];//每单提成
        String charges_type=map.get("charges_type")[0];//收费类型
        String endTime=map.get("endTime")[0];//到期时间
        String sql="UPDATE shop SET " +
                "merchant_name='"+merchant_name+"',phone='"+phone+"',adress='"+adress+"',per_commission='"+per_commission+"'" +
                ",charges_type='"+charges_type+"',endTime='"+endTime+"'  where id='"+id+"'";
        int i=Db.update(sql);
        if(i>0){
            returnData.setCode("000000");
            returnData.setMsg("成功");
        }else{
            returnData.setCode("111111");
            returnData.setMsg("失败");
        }
        return returnData;
    }

    /**
     * 微信发红包
     */
    public void payRebateRedPack(String shopId,String openId,String money,int rebateType,String memberId,String tickctorderId,String ticketId  ){

        AppletService appletService=new AppletService();

        boolean result=false;
        Map<String, String> params=new HashMap<>();
//        int rebateType=0;

        Record wxConfig=appletService.getWxConfig(shopId);

        String orderId=DateUtil.getDay()+Tools.getRandomNum();

        String apiclientPath= GlobalParameter.apiclientPath
                +wxConfig.getStr("mchId")+"/apiclient_cert.p12";
        Syslog.info("当前支付文件路径为："+apiclientPath);
        String xmlResult="";
        if (rebateType==0){//返利到红包d

            Syslog.info("返利到红包");

            params.put("nonce_str", UtilUUID.getOrderIdByUUId());
            params.put("mch_billno",UtilUUID.getOrderIdByUUId());
            String mchId=wxConfig.getStr("mchId");
            params.put("mch_id",mchId);
            params.put("wxappid",wxConfig.getStr("appId"));
            params.put("send_name","可乐自由行");
            params.put("re_openid",openId);
            params.put("total_amount",money);
            params.put("total_num","1");
            params.put("wishing","红包滚滚来");//红包祝福语
            params.put("client_ip","127.0.0.1");
            params.put("act_name","红包返利");
            params.put("remark","");
            String sign= PaymentKit.createSign(params,wxConfig.getStr("payKey"));
            params.put("sign",sign);
            Syslog.info("发送红包参数params:"+JsonUtil.getJsonStr(params));
            xmlResult= RedPackApi.sendRedPack(params,apiclientPath,mchId);
        }else  if (rebateType==1){//到零钱

            Syslog.info("返利到零钱");

            String url="https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
            params.put("nonce_str",UtilUUID.getOrderIdByUUId());
            params.put("partner_trade_no",UtilUUID.getOrderIdByUUId());
            String mchId=wxConfig.getStr("mchId");
            params.put("mchid",mchId);
            params.put("mch_appid",wxConfig.getStr("appId"));
            params.put("openid",openId);
            params.put("amount",money);
            params.put("check_name","NO_CHECK");//是否校验真实姓名
            //params.put("spbill_create_ip","127.0.0.1");
            params.put("spbill_create_ip","127.0.0.1");
            params.put("desc","分销返利");
            String sign=PaymentKit.createSign(params,wxConfig.getStr("payKey"));
            params.put("sign",sign);
            xmlResult= HttpUtils.postSSL(url,PaymentKit.toXml(params),apiclientPath,mchId);
        }
        Map<String, String> resultXML = PaymentKit.xmlToMap(xmlResult);
        Syslog.info(resultXML);
        String return_code = resultXML.get("return_code");
        String result_code = resultXML.get("result_code");
        Record record=new Record();
        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
            record.set("state","2");
        }else {
            record.set("openId",openId).set("money",money).set("id",orderId).set("errCode",resultXML.get("err_code"))
                    .set("errCodeDes",resultXML.get("err_code_des")).set("orderId",tickctorderId).set("ticketId",ticketId)
                    .set("memberId",memberId).set("type",rebateType).set("shopId",shopId);
            if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
                if ("SYSTEMERROR".equals(resultXML.get("err_code"))){//微信系统处理中
                    result = true;
                    record.set("state","1");
                }else {

                }
            }else {//微信发放成功
                record.set("state",0);
                result = true;
            }
            Db.save("yx_rebate_log",record);
        }
//        return result;


    }


    /**
     * 更换图标
     * @param map
     * @param shopId
     * @return
     */
    public ReturnData uoloadShopIcon(Map<String,String[]>map,String shopId){
        ReturnData returnData = new ReturnData();
        String haibao = map.get("haibao")[0]; //海报
        String callIcon = map.get("callIcon")[0];//电话图标啊哦
        String serviceIcon = map.get("serviceIcon")[0]; //客服图标
        String qRcodeimg = map.get("qRcodeimg")[0]; //二维码图片
        String serviceTel = map.get("serviceTel")[0]; //客服电话
        String aboutUs = map.get("aboutUs")[0]; //关于我们
        String sql="SELECT * FROM shop WHERE id='"+shopId+"'";
        try {
            Record record =Db.findFirst(sql);
            record.remove("poster").remove("callIcon").remove("serviceIcon");
            record.set("poster",haibao).set("callIcon",callIcon).set("serviceIcon",serviceIcon).set("qRcodeimg",qRcodeimg).set("serviceTel",serviceTel)
                    .set("aboutUs",aboutUs);
            Db.update("shop",record);

            returnData.setResult(true);
            returnData.setCode("0");
            returnData.setMsg("待支付订单创建成功");
        } catch (Exception e) {
            e.printStackTrace();
            returnData.setCode("1");
            returnData.setMsg("信息异常");
        }
        return returnData;
    }

    /**
     * 店铺详情
     * @param shopId
     * @return
     */
    public Record shopDetail(String shopId){
        String sql="SELECT * FROM shop WHERE id='"+shopId+"'";
        return Db.findFirst(sql);
    }
    /**
     * 修改显示加盟商
     * @param id
     * @return
     */
    public Record updaShopShowService(String id){

        String sql="SELECT * FROM shop WHERE id='"+id+"'";

        Record record=Db.findFirst(sql);

        return record;

    }

    /**
     * 删除优惠卷
     */
    public ReturnData delCoupon(String id){
        ReturnData returnData = new ReturnData();
        String sql="DELETE FROM yx_coupon where id='"+id+"'";
        int i=Db.delete(sql);
        if(i>0){
            returnData.setCode("000000");
            returnData.setMsg("成功");
        }else{
            returnData.setCode("111111");
            returnData.setMsg("失败");
        }
        return returnData;
    }
    /**
     * 查询商品标签
     */
    public PageUtil seleBrand(String page, String limit,String commodityId){
        String sql = "select *  FROM ticket_label where ticketId = '"+commodityId+"'";
        String countsql = " select count(*) FROM ticket_label where ticketId='"+commodityId+"'";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page),Integer.parseInt(limit),sql,countsql);
        return  pageUtil;
    }
    /**
     * 修改添加商品
     */
    public ReturnData addLabel(Map<String,String[]>map){
        String id = map.get("id")[0];
        String content = map.get("content")[0];
        String number = map.get("number")[0];
        String ticketId = map.get("ticketId")[0];

        ReturnData returnData = new ReturnData();
        boolean flag = false;

        if ("".equals(id)){
            flag = Db.save("ticket_label",new Record().set("id",UtilUUID.getUUID())
                    .set("content",content).set("number",number).set("ticketId",ticketId));

        }else {
            flag = Db.update("ticket_label","id",new Record().set("id",id).set("content",content).set("number",number).set("ticketId",ticketId));
        }
        if (flag){
            returnData.setCode("000000");
            returnData.setMsg("插入成功");
        }else {
            returnData.setCode("111111");
            returnData.setMsg("插入失败");
        }
        return  returnData;
    }

    /**
     * 修改显示
     * @param id
     * @return
     */
    public Record disPlay(String id){
        String sql = "SELECT * FROM ticket_label where id='"+id+"'";
        Record record = Db.findFirst(sql);
        return  record;
    }

    /**
     * 删除商品标签
     * @param id
     * @return
     */
    public ReturnData removeTags(String id){
        String sql = "DELETE FROM ticket_label where id='"+id+"'";
        int as = 0;
        as = Db.delete(sql);
        ReturnData returnData = new ReturnData();
        if (as==1){
            returnData.setCode("000000");
            returnData.setMsg("删除成功");
        }else {
            returnData.setCode("111111");
            returnData.setMsg("删除失败");
        }
        return  returnData;
    }
    /**
     * 根据商户id查找提现会员
     */
    public List<Record> getWithdrawerByShopId(String shopId,String name){




        String memberSql="select *from yx_member where shopId='"+shopId;

        if (name==null ||"".equals(name)){
            memberSql+="' order by  withdrawer ";
        }else {
            memberSql+="' and name like '%"+name+"%'  order by  withdrawer ";
        }

        memberSql+=" limit 0,6";
        List<Record> memberList=Db.find(memberSql);


        return memberList;

    }

    /**
     * 取票方式
     */
    public PageUtil ticketMethod(String page, String limit,String shopId) {
        String sql = "SELECT * FROM ticket_method where shopId='"+shopId+"'";
        String countSql = "SELECT count(*) FROM ticket_method   where shopId='"+shopId+"'";
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }

    public Record ticketMethodadd(String id){
        String sql="SELECT * FROM ticket_method WHERE id='"+id+"'";
        return Db.findFirst(sql);
    }

    public ReturnData addticketMethod(Map<String , String[] > map,String shopId){
        ReturnData returnData=new ReturnData();
        String id=map.get("id")[0];
        String name=map.get("name")[0];
        String number=map.get("number")[0];
        try {

            Record record=new Record();  //取票方式
            if(id!=null && !"".equals(id)) {
                record.set("name", name).set("number", number).set("shopId", shopId).set("id",id );
                Db.update("ticket_method","id", record);
            }else {
                record.set("name", name).set("number", number).set("shopId", shopId).set("id", UtilUUID.getUUID());
                Db.save("ticket_method", record);
            }
            returnData.setResult(true);
        }catch (Exception e){
            e.printStackTrace();
            returnData.setResult(false);
        }
        return returnData;
    }
    public ReturnData delticketMethod(String id){
        ReturnData returnData=new ReturnData();
        String sql="SELECT * FROM ticket_method WHERE id='"+id+"'";
        Record record= Db.findFirst(sql);
        Db.delete("ticket_method",record);
        return returnData;

    }
    /**
     * 保存提现人
     */
    public ReturnData saveSettingWithdrawerService(String shopId,String memberId,String checked){




        String upSql="UPDATE yx_member set withdrawer = 0 where shopId='"+shopId+"'";

        Db.update(upSql);

        if ("true".equals(checked)){

            upSql="UPDATE yx_member set withdrawer = 1 where id='"+ memberId+"'";

            Db.update(upSql);
        }

        return new ReturnData(true);
    }

    public PageUtil distributorList(String page, String limit, String userId,String memberName) {
        String shopSql="SELECT * FROM shop WHERE sys_user_id='"+userId+"'";
        Record record=Db.findFirst(shopSql);

        String shopId=record.get("id");
        String sql = " SELECT * FROM yx_member WHERE apply='2' AND shopId='"+shopId+"' ";
        String countSql = "  SELECT count(id) FROM yx_member WHERE apply='2' AND shopId='"+shopId+"'";
        if(memberName!=null && !"".equals(memberName)){
            sql+=" and name LIKE '%"+memberName+"%'";
            countSql+=" and name LIKE '%"+memberName+"%'";

        }
        PageUtil pageUtil = new PageUtil(Integer.parseInt(page), Integer.parseInt(limit), sql, countSql);
        return pageUtil;
    }

    /**
     * 返利记录
     * @param money
     * @param openId
     * @param memberId
     * @param state
     * @param type
     * @param errCode
     * @return
     */

    public ReturnData addrebateRecord(String orderId,int money, String openId,String memberId,String state,String type ,String errCode){
        ReturnData returnData=new ReturnData();
        try {
            Record record=new Record();  //返利记录
            String id=String.valueOf(System.currentTimeMillis());
            record.set("money",money).set("openId",openId).set("memberId",memberId).set("state",state).set("type",type).set("errCode",errCode).set("id",id)
                    .set("orderId",orderId);
            Db.save("yx_rebate_log",record);
            returnData.setResult(true);
        }catch (Exception e){
            e.printStackTrace();
            returnData.setResult(false);
        }
        return returnData;
    }

    public PageUtil rebateRecord(int page,int limit,String userId,String memberName,String shopId){
        String sql="SELECT a.id,a.money,b.`name` AS membername,d.`name` AS ticketName,c.number,a.createTime,a.state,a.type,a.errCodeDes  " +
                "FROM yx_rebate_log a LEFT JOIN yx_member b ON a.memberId=b.id LEFT JOIN yx_order c ON a.orderId=c.id LEFT JOIN " +
                "ticket d ON a.ticketId=d.id where a.shopId='"+shopId+"'";
        PageUtil pageUtil=new PageUtil(page,limit,sql);
        return pageUtil;
    }
}
